<?php
/**
 * Created by User: wene<china_wangyu@aliyun.com> Date: 2019/4/12 Time: 15:17
 */

namespace think\restful\validate;


use think\restful\Base;
use think\restful\exception\ApiException;

/**
 * Class Route API路由自检类
 * @package think\restful\validate
 */
class Route extends Base
{
    protected $route;

    public function __construct()
    {
        parent::__construct();
    }

    public function execute(\think\restful\route\Route $route):void
    {
        // TODO: Implement execute() method.
        try{
            $this->route = $route;
            $this->module();
            $this->version();
            $this->method();
            $this->action($route);
        }catch (\Exception $exception){
            ApiException::exception('500 '.$exception->getMessage());
        }
    }

    /**
     * 验证模块是否正确
     */
    protected function module():void {
        empty($this->route->module) && ApiException::exception('404 参数不能为空: ' . $this->route->module);
        if(!is_dir(env('APP_PATH') . $this->route->module)){
            ApiException::exception('404 注册模块不存在: ' . $this->route->module);
        }
    }

    /**
     * 检验版本是否合法
     */
    protected function version():void {
        try{
            empty($this->route->version) && ApiException::exception('404 参数不能为空: ' .$this->route->version);
            if(!in_array($this->route->version,$this->config['API_VERSION'])){
                ApiException::exception('404 当前API版本没有访问权限: ' . $this->route->version);
            }
            if(!is_dir(env('APP_PATH'). $this->route->module.DIRECTORY_SEPARATOR.
                $this->config['API_CONTROLLER'].DIRECTORY_SEPARATOR. $this->route->version)){
                ApiException::exception('404 访问API版本不存在: ' . $this->route->version);
            }
        }catch (\Exception $exception){
            ApiException::exception('500 '.$exception->getMessage());
        }

    }

    /**
     * 验证请求类型是否存在，验证请求类型是否系统指定方法名称
     */
    protected function method():void {
        $method = request()->method();
        $methods = empty($this->config['API_METHOD_DEFAULT_ACTION']) ?
            ['GET','POST','PUT','DELETE','PATCH','HEAD','OPTIONS']:
            array_keys($this->config['API_METHOD_DEFAULT_ACTION']);
        !in_array(strtoupper($method),$methods) && ApiException::exception('403 请求类型错误，你的请求方式为：'.$method);
    }

    /**
     * 验证请求方法是否存在
     * @param \think\restful\route\Route $route
     */
    protected function action(\think\restful\route\Route $route):void {
        try {
            $apiNamespace = DIRECTORY_SEPARATOR . $route->module .
                DIRECTORY_SEPARATOR . $this->config['API_CONTROLLER'] . DIRECTORY_SEPARATOR . $route->version .
                DIRECTORY_SEPARATOR . ucwords($route->controller);
            if (!is_file(env('APP_PATH') . $apiNamespace . '.php')) {
                ApiException::exception('请求 ' . $route->controller . ' 不存在~');
            }
            $apiNamespace = str_ireplace('/','\\',DIRECTORY_SEPARATOR . env('APP_NAMESPACE') . $apiNamespace);
            $apiObject = new $apiNamespace(true);
            if(!method_exists($apiObject, $route->action)){
                $action = $this->config['API_METHOD_DEFAULT_ACTION'][$this->request->method()];
                !method_exists($apiObject, $action) && ApiException::exception('请求 action 不存在~');
                $route->action = $action;
            }
        } catch (\Exception $exception) {
            ApiException::exception('404 ' . $exception->getMessage());
        }
    }
}